from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse
import urllib
import json
from datetime import datetime
from models import Form
from models import Division
from models import AgeGroup
from models import Sex
from models import Event
import time

HOST = 'http://192.168.1.102'
GET_URL = '%s/cmat18/server/api/get.php' % HOST
SET_URL = '%s/cmat18/server/api/set.php' % HOST
NUM_RINGS = 8

def update(request):
  # Syncs Ring, Form, Division, AgeGroup, Sex, and Event
  
  for form_record in get('form')['records']:
    form, created = Form.objects.get_or_create(pk=form_record['id'])
    form.code = form_record['shortName']
    form.name = form_record['longName']
    form.save()
    
  for level_record in get('division')['records']:
    division, created = Division.objects.get_or_create(pk=level_record['id'])
    division.code = level_record['shortName']
    division.name = level_record['longName']
    division.save()
  
  for age_group_record in get('ageGroup')['records']:
    age_group, created = AgeGroup.objects.get_or_create(pk=age_group_record['id'])
    age_group.code = age_group_record['shortName']
    age_group.name = age_group_record['longName']
    age_group.save()
    
  for sex_record in get('sex')['records']:
    sex, created = Sex.objects.get_or_create(pk=sex_record['id'])
    sex.code = sex_record['shortName']
    sex.name = sex_record['longName']
    sex.save()
    
  for event_record in get('event')['records']:
    event, created = Event.objects.get_or_create(pk=event_record['id'], defaults={
      'ring': event_record['ringId'],
      'order': event_record['order'],
      'code': event_record['code'],
      'num_competitors': event_record['numCompetitors'],
      'completed': event_record['isFinished'],
      'division': Division.objects.get(pk=event_record['divisionId']),
      'age_group': AgeGroup.objects.get(pk=event_record['ageGroupId']),
      'form': Form.objects.get(pk=event_record['formId']),
      'sex': Sex.objects.get(pk=event_record['sexId']),
    })
    event.save()
    
  return redirect('/', None, 'Update successful')

def get(type, field=None, value=None):
  data = {'type': type}
  if field:
    data['filterField'] = field
    data['filterValue'] = value
  u = urllib.urlopen(GET_URL, urllib.urlencode(data))
  s = u.read()
  return json.loads(s)

def set(op, type, records):
  data = {
    'op': op,
    'type': type,
    'records': records or []
  }
  u = urllib.urlopen(SET_URL, urllib.urlencode(data))
  return u.read()
  
def event(request, code): 
  response = {}
  event = Event.objects.get(code=code)
  event_record = get('event', 'id', event.pk)['records'][0]
  if event.completed != event_record['isFinished']:
    event.end_time = datetime.now()
    event.completed = event_record['isFinished']
    event.save()
  scoring = get('scoring', 'eventId', event.pk)['records']
  for score in scoring:
    score['competitor'] = get('competitor', 'id', score['competitorId'])['records'][0]
  response['event'] = event
  response['scores'] = scoring
  response['get_url'] = GET_URL
  response['set_url'] = SET_URL
  response['is_nandu'] = 'true' if event.division.code == 'N' else 'false'
  return render_to_response('event.html', response)
  
def start_event(request, id): 
  response = {}
  event = Event.objects.get(pk=id)
  event.ongoing = True
  event.start_time = datetime.now()
  event.save()
  return HttpResponse(json.dumps({'success': 'true'}))
  
def get_proxy(request):
  return HttpResponse(json.dumps(get(
      request.GET['type'],
      request.GET['filterField'] or None,
      request.GET['filterValue'] or None)))
      
def set_proxy(request):
  if request.GET['op'] == 'edit' and request.GET['type'] == 'event':
    for event_record in json.loads(request.GET['records']):
      event = Event.objects.get(pk=event_record['id'])
      if event.completed != event_record['isFinished']:
        event.end_time = datetime.now()
        event.completed = event_record['isFinished']
        event.save()
  return HttpResponse(set(request.GET['op'], request.GET['type'], request.GET['records']))

def index(request, ring_number=None):
  response = {}
  response['rings'] = []
  for ring in range(1, NUM_RINGS + 1):
    ring_events = Event.objects.filter(ring=ring)
    response['rings'].append((
        ring,
        len(ring_events),
        len(ring_events.filter(completed=False))
    ))
  if ring_number:
    response['ring'] = int(ring_number)
    event_records = get('event', 'ringId', ring_number)['records']
    for event_record in event_records:
      event = Event.objects.get(pk=event_record['id'])
      if event.completed != event_record['isFinished']:
        event.end_time = datetime.now()
        event.completed = event_record['isFinished']
        event.save()
  response['events'] = Event.objects.filter(ring=ring_number).order_by('order')
  next_events = Event.objects.filter(ring=ring_number, completed=False).order_by('order')
  if next_events:
    response['next_event'] = next_events[0]
  else:
    response['next_event'] = None
  return render_to_response('index.html', response)
